#ifndef __M_BENCH2_H__
#define __M_BENCH2_H__

#include "../Logs/cl_logs.hpp"
#include <chrono>

namespace cl{
void bench(const std::string& logger_name, size_t thread_num, size_t msg_num, size_t msg_len) {
    // 获取日志器
    Logger::ptr logger = getLogger(logger_name);
    if (logger.get() == nullptr) { return; }
    std::cout << "测试日志: " << msg_num << " 条,总大小: " << msg_num * msg_len / 1024 << "KB" << std::endl;
    // 组织指定长度的日志消息
    std::string msg(msg_len - 1, 'A'); //-1是为了添加\n
    
    // 创建指定数量的线程
    std::vector<std::thread> threads;
    std::vector<double> cost_array(thread_num);    //记录各个线程的消耗时间
    size_t per_num = msg_num / thread_num;
    for (size_t i = 0; i < thread_num; i++) {
        threads.emplace_back([&, i]() {
            // 开始测试
            int num = per_num;
            if (i + 1 == thread_num)
                num += (msg_num % thread_num);
            auto start = std::chrono::high_resolution_clock::now();
            for (int i = 0; i < num; i++) {
                logger->fatal("%s", msg.c_str());
            }
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - start;
            cost_array[i] = cost.count(); 
        });
    }
    for (size_t i = 0; i < thread_num; i++) {
        threads[i].join();
    }
    // 计算总耗时,求并发最大值
    double max_cost = 0;
    for (size_t i = 0; i < cost_array.size(); i++) {
        if (cost_array[i] > max_cost)
            max_cost = cost_array[i];
        if (i + 1 == thread_num)
            per_num += (msg_num % thread_num);
        std::cout << "线程" << i + 1 << ": "
            << "\t输出日志数量: " << per_num << ",耗时: " << cost_array[i] << "s" << std::endl;
    }
 
    size_t per_sec_msg = msg_num / max_cost;
    size_t per_sec_size = per_sec_msg * msg_len / 1024;
 
    std::cout << "\t总耗时: " << max_cost << "s" << std::endl;
    std::cout << "\t每秒输出日志数量: " << per_sec_msg << "条" << std::endl;
    std::cout << "\t每秒输出日志大小: " << per_sec_size << "KB" << std::endl;
}
}

#endif